package com.lyw.forum.controller;

import com.lyw.forum.common.enums.ResultCode;
import com.lyw.forum.pojo.request.ArticleCreateRequest;
import com.lyw.forum.pojo.request.ArticleUpdateRequest;
import com.lyw.forum.pojo.response.AppResult;
import com.lyw.forum.pojo.response.ArticleSelectResponse;
import com.lyw.forum.pojo.response.BoardSelectResponse;
import com.lyw.forum.pojo.response.UserSelectResponse;
import com.lyw.forum.service.IArticleService;
import com.lyw.forum.service.IBoardService;
import com.lyw.forum.service.IUserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author lyw
 */

@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private IArticleService articleService;

    @Resource
    private IBoardService boardService;

    @Resource
    private IUserService userService;

    /**
     * 发布帖子
     * @param articleCreateRequest 帖子信息
     * @return
     */
    @RequestMapping("/create")
    public AppResult create(@Validated @RequestBody ArticleCreateRequest articleCreateRequest, HttpServletRequest request) {
        //获取板块用户的id
        String id = request.getHeader("id");

        if (id == null || !StringUtils.hasLength(id)) {
            //打印日志
            log.error(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //返回响应
            return AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        //根据用户id查询用户信息
        UserSelectResponse userSelectResponse = userService.selectById(Integer.parseInt(id));

        //校验用户是否被禁言
        if (userSelectResponse.getState() == 1) {
            //用户已禁言
            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }

        //板块校验
        BoardSelectResponse boardSelectResponse = boardService.selectById(articleCreateRequest.getBoardId());

        if (boardSelectResponse == null || boardSelectResponse.getState() == 1 || boardSelectResponse.getDeleteState() == 1) {
            //打印日志
            log.error(ResultCode.FAILED_BOARD_BANNED.toString());
            //返回响应
            return AppResult.fail(ResultCode.FAILED_BOARD_BANNED);
        }

        //设置发帖人id
        articleCreateRequest.setUserId(userSelectResponse.getId());

        //调用service
        articleService.creat(articleCreateRequest);

        //返回结果
        return AppResult.success();

    }

    /**
     * 查询所有帖子
     * @return
     */
    @RequestMapping("/getAllByBoardId")
    public AppResult<List<ArticleSelectResponse>> getAllByBoardId(@RequestParam(value = "boardId", required = false) Integer boardId) {
        //定义返回集合
        List<ArticleSelectResponse> articleSelectResponses;

        if (boardId == null) {
            //查询所有
            articleSelectResponses = articleService.selectAll();
        } else {
            //查询指定板块
            articleSelectResponses = articleService.selectAllByBoardId(boardId);
        }

        //判断结果是否为空
        if (articleSelectResponses == null) {
            //如果为空, 就创建空集合
            articleSelectResponses = List.of();
        }

        //响应结果
        return AppResult.success(articleSelectResponses);

    }

    /**
     * 获取帖子详情
     * @param id 帖子id
     * @return
     */
    @RequestMapping("/getDetailById")
    public AppResult<ArticleSelectResponse> getDetailById(@NotNull(message = "帖子id不能为空") Integer id) {
        //调用service 获取帖子详情
        ArticleSelectResponse articleSelectResponse = articleService.selectDetailById(id);

        //判断结果是否为空
        if (articleSelectResponse == null) {
            //打印日志
            log.error(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //返回响应
            return AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        //返回结果
        return AppResult.success(articleSelectResponse);
    }

    /**
     * 修改帖子
     * @param articleUpdateRequest 帖子信息
     * @return
     */
    @RequestMapping("/modify")
    public AppResult modify(@RequestBody @Validated ArticleUpdateRequest articleUpdateRequest, HttpServletRequest request) {
        //获取当前用户信息
        String id = request.getHeader("id");

        if (id == null || !StringUtils.hasLength(id)) {
            //打印日志
            log.error(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //返回响应
            return AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        UserSelectResponse userSelectResponse = userService.selectById(Integer.parseInt(id));

        //校验用户状态
        if (userSelectResponse.getState() == 1) {
            //返回错误信息
            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }

        //查询帖子信息
        ArticleSelectResponse articleSelectResponse = articleService.selectById(articleUpdateRequest.getId());

        //判断帖子是否有效
        if (articleSelectResponse == null) {
            //返回错误信息
            return AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        //判断用户是否是帖子的作者
        if (!articleSelectResponse.getUserId().equals(userSelectResponse.getId())) {
            //返回错误信息
            return AppResult.fail(ResultCode.FAILED_FORBIDDEN);
        }

        //调用 service
        articleService.modify(articleUpdateRequest);

        //打印日志
        log.info("修改帖子成功, articleId: " + articleUpdateRequest.getId() + ", userId: " + userSelectResponse.getId());

        //返回结果
        return AppResult.success();
    }

    /**
     * 点赞
     * @param id 帖子id
     * @return 响应结果
     */
    @RequestMapping("/thumbsUp")
    public AppResult thumbsUpById(@NotNull(message = "帖子id不能为空") Integer id, HttpServletRequest request) {
        //获取当前用户信息
        String userId = request.getHeader("id");

        if (userId == null || !StringUtils.hasLength(userId)) {
            //打印日志
            log.error(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //返回响应
            return AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        UserSelectResponse userSelectResponse = userService.selectById(Integer.parseInt(userId));

        //判断用户是否被禁言
        if (userSelectResponse.getState() == 1) {
            //用户已禁言 打印日志
            log.error(ResultCode.FAILED_USER_BANNED.toString());
            //返回结果
            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }

        //调用service
        articleService.thumbsUpById(id);

        //返回结果
        return AppResult.success();
    }

    @RequestMapping("/delete")
    public AppResult deleteById(@NotNull(message = "帖子id不能为空") Integer id, HttpServletRequest request) {
        //获取当前用户信息
        String userId = request.getHeader("id");

        if (userId == null || !StringUtils.hasLength(userId)) {
            //打印日志
            log.error(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //返回响应
            return AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        //查询用户信息
        UserSelectResponse userSelectResponse = userService.selectById(Integer.parseInt(userId));

        //判断用户是否被禁言
        if (userSelectResponse.getState() == 1) {
            //用户已禁言 打印日志
            log.error(ResultCode.FAILED_USER_BANNED.toString());
            //返回结果
            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }

        //查询帖子详情
        ArticleSelectResponse articleSelectResponse = articleService.selectById(id);

        if (articleSelectResponse == null || articleSelectResponse.getDeleteState() == 1) {
            //打印日志
            log.error(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //返回响应
            return AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        //调用service 删除帖子
        articleService.deleteById(id);

        //返回结果
        return AppResult.success();
    }

    @RequestMapping("/getAllByUserId")
    public AppResult getAllByUserId(@RequestParam(required = false) Integer id, HttpServletRequest request) {
        //判断id是否为空
        if (id == null) {
            String userId = request.getHeader("id");
            id = Integer.parseInt(userId);
        }

        //根据id查询用户信息
        List<ArticleSelectResponse> articleSelectResponses = articleService.selectByUserId(id);

        //返回结果
        return AppResult.success(articleSelectResponses);
    }
}
